import { useEffect, useRef } from "react";
import {
    ArcRotateCamera, Color4, Engine, HemisphericLight, Mesh, MeshBuilder, Plane, Scene, UniversalCamera,
    StandardMaterial, Vector3, Color3, DirectionalLight, Animation, CircleEase, EasingFunction,
} from '@babylonjs/core';
import Play from '../component/Player';


const canvas = document.createElement("canvas");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

const engine = new Engine(canvas, true);
const scene = new Scene(engine);


// const camera1 = new ArcRotateCamera('Camera', Math.PI / 3, Math.PI / 3, 20, new Vector3(0, 0, 0), scene);
// camera1.attachControl(canvas, true);

const camera = new UniversalCamera('Camera', new Vector3(7, 7, 7), scene);
camera.setTarget(new Vector3(0, 2, 0));
camera.attachControl(canvas, true);

const updateAction: ((time: number) => {})[] = [];

const light = new HemisphericLight('pxg', new Vector3(1, 1, 0), scene);
// const light = new DirectionalLight('light02', new Vector3(1, -1, 1), scene);
const ground = MeshBuilder.CreateGround('ground', { width: 20, height: 20, updatable: true }, scene);

const box = MeshBuilder.CreateBox('box', {
    width: 2,
    height: 2,
    depth: 2,
    faceColors: [
        new Color4(1, 0, 0, 1),
        new Color4(0, 1, 0, 1),
        new Color4(0, 0, 1, 1),
        new Color4(1, 1, 0, 1),
        new Color4(0, 1, 1, 1),
        new Color4(1, 0, 1, 1),
    ],
    sideOrientation: 2,
}, scene);
box.position.set(0, 5, 0);

//重力值
scene.gravity = new Vector3(0, -9.81, 0);
camera.applyGravity = true;//第三人称相机需要另类设置
camera.ellipsoid = new Vector3(1, 1, 1);//相机的碰撞体积

//开启碰撞
scene.collisionsEnabled = true;
camera.checkCollisions = true;
box.checkCollisions = true;
ground.checkCollisions = true;




// const play = new Play(camera);
// play.start();



const RenderStructure = () => {
    const divRef = useRef<HTMLDivElement>(null);
    useEffect(() => {
        const { current } = divRef;
        if (current != null) {
            current.innerHTML = '';
            current.append(canvas);
            ani(0);
        }
    }, []);
    return (
        <div ref={divRef}></div>
    );
};

export default RenderStructure;


function ani(time: number) {
    updateAction.forEach((action) => {
        action(time);
    })
    scene.render();

    requestAnimationFrame(ani);
}